package com.hualude.roadsign.repository;

import com.hualude.roadsign.dto.CoverDto;
import com.hualude.roadsign.dto.CoverFaultDto;
import com.hualude.roadsign.dto.DTRequestDto;
import com.hualude.roadsign.dto.FaultCountDto;
import org.hibernate.query.NativeQuery;
import org.hibernate.transform.Transformers;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import java.util.List;

import static com.hualude.roadsign.service.impl.CountServiceImpl.convertParams;

/**
 * Created by ding on 2017/9/22.
 */
public class CoverFaultCountRepositoryImpl {

    @PersistenceContext
    private EntityManager em;

    public List<String> getDealCounts(Integer year, String orgIds) throws Exception {
        Integer yearNext = year + 1;
        String hql = "select m.CoverMaintenanceTime from tb_cover_fault m,tb_user u where m.CoverMaintenanceStatus = 2 and " +
                "(m.CoverMaintenanceTime between '" + year + "' and '" + yearNext + "') and m.CoverMaintainerId = u.userId and u.orgId in (" + orgIds + ")";
        Query query = em.createNativeQuery(hql);
        List<String> times = query.getResultList();
        return times;
    }

    public List<String> getReportCounts(Integer year, String orgIds) throws Exception {
        Integer yearNext = year + 1;
        String hql = "select s.CoverFaultTime from tb_cover_fault s where " +
                "(s.CoverFaultTime between '" + year + "' and '" + yearNext + "') and  (s.CoverOrgId in (" + orgIds + ") or " +
                "s.CoverMainOrgId in (" + orgIds + "))";
        Query query = em.createNativeQuery(hql);
        List<String> times = query.getResultList();
        return times;
    }

    public List<FaultCountDto> getExpenseCounts(Integer year, String orgIds) throws Exception {
        Integer yearNext = year + 1;
        String hql = "select m.CoverMaintenanceTime AS maintenanceTime,m.CoverMoney AS repairAmount from tb_cover_fault m,tb_user u where " +
                "(m.CoverMaintenanceTime between '" + year + "' and '" + yearNext + "') and m.CoverMaintainerId = u.userId and u.orgId in (" + orgIds + ")";
        Query query = em.createNativeQuery(hql);
        query.unwrap(NativeQuery.class).setResultTransformer(Transformers.aliasToBean(FaultCountDto.class));
        List<FaultCountDto> maintenanceDtos = query.getResultList();
        return maintenanceDtos;
    }

    public List<CoverFaultDto> getFault4DT(DTRequestDto dtRequestDto, Integer actor, String orgIds) throws Exception {
        String hql = "select f.CoverFaultId,f.CoverId,f.CoverFaultPhoto,p.CoverPhoto,f.CoverFaultLevel,f.CoverCheck,f.CoverMainCheck,\n" +
                "f.CoverFaultTime,f.CoverCheckTime,o.OrgName AS coverOrgName,o2.orgName as coverMainOrgName,p.CoverPeriod," +
                " p.CoverStartRoad,p.CoverEndRoad,p.CoverRoadName,p.CoverServiceLife,p.CoverShape,p.CoverMaterial,p.CoverSize,\n" +
                "p.CoverArea,p.CoverCity,p.CoverProvince,u.UserName AS coverFaultCreatorName\n" +
                "from tb_cover_fault f,tb_org o,tb_org o2,tb_cover p,tb_user u\n" +
                "where f.CoverOrgId = o.OrgId and p.CoverMainOrgId=o2.orgId and f.CoverId = p.CoverId  AND\n" +
                "f.CoverFaultCreatorId = u.UserId";
        String[] sQuery = convertParams(dtRequestDto.getSearch());
        String timeLimit = sQuery[0];
        if (!timeLimit.equals("-1") && timeLimit != "") {
            String[] dateStr = timeLimit.split(" - ");
            hql += " and f.CoverFaultTime between '" + dateStr[0] + "' and '" + dateStr[1] + 1 + "'";
        }
        if (!sQuery[1].equals("-1")) {
            hql += " and o.OrgId = " + sQuery[1];
        }
        if (actor != 1) {
            hql += " and (f.CoverOrgId IN (" + orgIds + ") or " +
                    "f.CoverMainOrgId IN (" + orgIds + "))";
        }
        hql += " ORDER BY f.CoverFaultTime DESC";
        Query query = em.createNativeQuery(hql);
        query.unwrap(NativeQuery.class).setResultTransformer(Transformers.aliasToBean(CoverFaultDto.class));
        List<CoverFaultDto> roadpoleDto = query.setFirstResult(dtRequestDto.getStart()).setMaxResults(dtRequestDto.getLength()).getResultList();
        return roadpoleDto;
    }

    public Integer getFaultCount4DT(DTRequestDto dtRequestDto, Integer actor, String orgIds) throws Exception {
        String hql = "select count(*) from tb_cover_fault f,tb_org o WHERE f.CoverOrgId= o.OrgId";
        String[] sQuery = convertParams(dtRequestDto.getSearch());
        String timeLimit = sQuery[0];
        if (!timeLimit.equals("-1") && timeLimit != "") {
            String[] dateStr = timeLimit.split(" - ");
            hql += " and f.CoverFaultTime between '" + dateStr[0] + "' and '" + dateStr[1] + 1 + "'";
        }
        if (!sQuery[1].equals("-1")) {
            hql += " and o.OrgId = " + sQuery[1];
        }
        if (actor != 1) {
            hql += " and (f.CoverOrgId IN (" + orgIds + ") or " +
                    "f.CoverMainOrgId IN (" + orgIds + "))";
        }
        Query query = em.createNativeQuery(hql);
        Integer count = Integer.parseInt(query.getSingleResult().toString());
        return count;
    }

    public List<CoverFaultDto> getDevice4DT(DTRequestDto dtRequestDto, Integer actor, String orgIds, Integer userId) throws Exception {
        String hql = "select m.CoverFaultId,m.CoverFaultPhoto,m.CoverMaintenancePhoto,m.CoverMaintenanceStatus,m.CoverMaintenanceTime,CoverMoney,\n" +
                "o.OrgName AS coverOrgName,m.CoverId,s.CoverEndRoad,s.CoverStartRoad,s.CoverArea,s.CoverRoadName,s.CoverServiceLife,s.CoverShape,s.CoverMaterial,s.CoverSize,\n" +
                "s.CoverCity,s.CoverProvince,o2.orgName as coverMainOrgName,s.CoverPhoto,s.CoverPeriod,u.UserName AS coverFaultCreatorName\n" +
                "from tb_cover_fault m,tb_user u,tb_org o,tb_org o2,tb_cover s \n" +
                "where m.CoverMaintenanceStatus=2 and m.CoverMaintainerId = u.userId and s.CoverMainOrgId=o2.orgId\n" +
                "and u.OrgId = o.OrgId and m.CoverId = s.CoverId ";
        String[] sQuery = convertParams(dtRequestDto.getSearch());
        String timeLimit = sQuery[0];
        if (!timeLimit.equals("-1") && timeLimit != "") {
            String[] dateStr = timeLimit.split(" - ");
            hql += " and m.CoverMaintenanceTime between '" + dateStr[0] + "' and '" + dateStr[1] + "'";
        }
        if (!sQuery[1].equals("-1")) {
            hql += " and o.OrgId = " + sQuery[1];
        }
        if (actor != 1) {
            hql += " and (u.OrgId IN (" + orgIds + "))";
        }
        hql += " ORDER BY m.CoverMaintenanceTime DESC";
        Query query = em.createNativeQuery(hql);
        query.unwrap(NativeQuery.class).setResultTransformer(Transformers.aliasToBean(CoverFaultDto.class));
        List<CoverFaultDto> roadpoleDto = query.setFirstResult(dtRequestDto.getStart()).setMaxResults(dtRequestDto.getLength()).getResultList();
        return roadpoleDto;
    }

    public Integer getDeviceCount4DT(DTRequestDto dtRequestDto, Integer actor, String orgIds, Integer userId) throws Exception {
        String hql = "select count(*) from tb_cover_fault m,tb_user u,tb_org o,tb_org o2,tb_cover s \n" +
        "where m.CoverMaintenanceStatus=2 and m.CoverMaintainerId = u.userId and s.CoverMainOrgId=o2.orgId\n" +
                "and u.OrgId = o.OrgId and m.CoverId = s.CoverId ";
        String[] sQuery = convertParams(dtRequestDto.getSearch());
        String timeLimit = sQuery[0];
        if (!timeLimit.equals("-1") && timeLimit != "") {
            String[] dateStr = timeLimit.split(" - ");
            hql += " and m.CoverMaintenanceTime between '" + dateStr[0] + "' and '" + dateStr[1] + "'";
        }
        if (!sQuery[1].equals("-1")) {
            hql += " and o.OrgId = " + sQuery[1];
        }
        if (actor != 1) {
            hql += " and (u.OrgId IN (" + orgIds + "))";
        }
        Query query = em.createNativeQuery(hql);
        Integer count = Integer.parseInt(query.getSingleResult().toString());
        return count;
    }

    public Integer getCoverCount4DT(DTRequestDto dtRequestDto, Integer actor, String orgIds) throws Exception {
        String hql = "select count(*) from tb_cover where CoverId like '%'";
        String[] sQuery = convertParams(dtRequestDto.getSearch());
        //0:省 1:市 2:区域 3:道路 4:起始路段 5:终止路段 6:主管单位 7:养护公司
        if (!sQuery[0].equals("-1")) {
            hql += " and CoverProvince = '" + sQuery[0] + "'";
        }
        if (!sQuery[1].equals("-1")) {
            hql += " and CoverCity = '" + sQuery[1] + "'";
        }
        if (!sQuery[2].equals("-1")) {
            hql += " and CoverArea = '" + sQuery[2] + "'";
        }
        if (!sQuery[3].equals("-1")) {
            hql += " and CoverRoadName ='" + sQuery[3] + "'";
        }
        if (!sQuery[4].equals("-1") && sQuery[5].equals("-1")) {
            hql += " and (CoverStartRoad ='" + sQuery[4] + "' or CoverEndRoad ='" + sQuery[4] + "')";
        }
        if (sQuery[4].equals("-1") && !sQuery[5].equals("-1")) {
            hql += " and (CoverEndRoad ='" + sQuery[5] + "' or CoverStartRoad ='" + sQuery[5] + "')";
        }
        if (!sQuery[4].equals("-1") && !sQuery[5].equals("-1")) {
            hql += " and ((CoverStartRoad ='" + sQuery[4] + "' and CoverEndRoad ='" + sQuery[5] + "') or" +
                    "(CoverStartRoad = '" + sQuery[5] + "' and CoverEndRoad = '" + sQuery[4] + "'))";
        }
        if (!sQuery[6].equals("-1")) {
            hql += " and CoverMainOrgId = '" + sQuery[6] + "'";
        }
        if (!sQuery[7].equals("-1")) {
            hql += " and CoverOrgId = '" + sQuery[7] + "'";
        }
        if (actor != 1) {
            hql += " and (CoverOrgId IN (" + orgIds + ") or " +
                    "CoverMainOrgId IN (" + orgIds + "))";
        }
        Query query = em.createNativeQuery(hql);
        Integer count = Integer.parseInt(query.getSingleResult().toString());
        return count;
    }

    public List<CoverDto> getCover4DT(DTRequestDto dtRequestDto, Integer actor, String orgIds) throws Exception {
        String hql = "select c.CoverId,c.CoverPhoto,c.CoverProvince,c.CoverCity,c.CoverArea," +
                "c.CoverRoadName,e.OrgName as coverMainOrgName,o.OrgName as coverOrgName," +
                "c.CoverShape,c.CoverMaterial,c.CoverSize,c.CoverInstallTime,c.CoverStartRoad," +
                "c.CoverEndRoad,c.CoverIsComplete from tb_cover c " +
                "LEFT JOIN tb_org e ON c.CoverMainOrgId = e.OrgId " +
                "LEFT JOIN tb_org o ON c.CoverOrgId = o.OrgId " +
                "where c.CoverId LIKE '%'";
        String[] sQuery = convertParams(dtRequestDto.getSearch());
        //0:省 1:市 2:区域 3:道路 4:起始路段 5:终止路段 6:主管单位 7:养护公司
        if (!sQuery[0].equals("-1")) {
            hql += " and CoverProvince = '" + sQuery[0] + "'";
        }
        if (!sQuery[1].equals("-1")) {
            hql += " and CoverCity = '" + sQuery[1] + "'";
        }
        if (!sQuery[2].equals("-1")) {
            hql += " and CoverArea = '" + sQuery[2] + "'";
        }
        if (!sQuery[3].equals("-1")) {
            hql += " and CoverRoadName ='" + sQuery[3] + "'";
        }
        if (!sQuery[4].equals("-1") && sQuery[5].equals("-1")) {
            hql += " and (CoverStartRoad ='" + sQuery[4] + "' or CoverEndRoad ='" + sQuery[4] + "')";
        }
        if (sQuery[4].equals("-1") && !sQuery[5].equals("-1")) {
            hql += " and (CoverEndRoad ='" + sQuery[5] + "' or CoverStartRoad ='" + sQuery[5] + "')";
        }
        if (!sQuery[4].equals("-1") && !sQuery[5].equals("-1")) {
            hql += " and ((CoverStartRoad ='" + sQuery[4] + "' and CoverEndRoad ='" + sQuery[5] + "') or" +
                    "(CoverStartRoad = '" + sQuery[5] + "' and CoverEndRoad = '" + sQuery[4] + "'))";
        }
        if (!sQuery[6].equals("-1")) {
            hql += " and CoverMainOrgId = '" + sQuery[6] + "'";
        }
        if (!sQuery[7].equals("-1")) {
            hql += " and CoverOrgId = '" + sQuery[7] + "'";
        }
        if (actor != 1) {
            hql += " and (CoverOrgId IN (" + orgIds + ") or " +
                    "CoverMainOrgId IN (" + orgIds + "))";
        }
        hql += " ORDER BY c.CoverInstallTime DESC";
        Query query = em.createNativeQuery(hql);
        query.unwrap(NativeQuery.class).setResultTransformer(Transformers.aliasToBean(CoverDto.class));
        List<CoverDto> monitorDtos = query.setFirstResult(dtRequestDto.getStart()).setMaxResults(dtRequestDto.getLength()).getResultList();
        return monitorDtos;
    }

    public List<String> getProvinceName(String orgIds) throws Exception {
        String hql = "select distinct c.CoverProvince from tb_cover c where c.CoverOrgId in (" + orgIds + ") or " +
                "c.CoverMainOrgId in (" + orgIds + ")";
        hql += " order by convert(c.CoverProvince using gbk) asc";
        Query query = em.createNativeQuery(hql);
        List<String> province = query.getResultList();
        return province;
    }

    public List<String> getCityName(String orgIds, String provinceName) throws Exception {
        String hql = "select distinct c.CoverCity from tb_cover c where (c.CoverOrgId in (" + orgIds + ") or " +
                "c.CoverMainOrgId in (" + orgIds + "))";
        if (!provinceName.equals("-1")) {
            hql += " and c.CoverProvince = '" + provinceName + "'";
        }
        hql += " order by convert(c.CoverCity using gbk) asc";
        Query query = em.createNativeQuery(hql);
        List<String> city = query.getResultList();
        return city;
    }

    public List<String> getAllAreaName(String orgIds, String provinceName, String cityName) throws Exception {
        String hql = "select distinct c.CoverArea from tb_cover c where (c.CoverOrgId IN (" + orgIds + ")" +
                " or c.CoverMainOrgId IN (" + orgIds + "))";
        if (!provinceName.equals("-1")) {
            hql += " and c.CoverProvince ='" + provinceName + "'";
        }
        if (!cityName.equals("-1")) {
            hql += " and c.CoverCity ='" + cityName + "'";
        }
        hql += " order by convert(c.CoverArea using gbk) asc";
        Query query = em.createNativeQuery(hql);
        List<String> area = query.getResultList();
        return area;
    }

    public List<String> getRoadNames(String provinceName, String cityName, String areaName, String orgId, Integer actor) throws Exception {
        String hql = "select distinct c.CoverRoadName from tb_cover c where (c.CoverOrgId in (" + orgId + ") or " +
                "c.CoverMainOrgId in (" + orgId + "))";
        if (!provinceName.equals("-1")) {
            hql += " and c.CoverProvince ='" + provinceName + "'";
        }
        if (!cityName.equals("-1")) {
            hql += " and c.CoverCity ='" + cityName + "'";
        }
        if (!areaName.equals("-1")) {
            hql += " and c.CoverArea = '" + areaName + "'";
        }
        hql += " order by convert(c.CoverRoadName using gbk) asc";
        Query query = em.createNativeQuery(hql);
        List<String> road = query.getResultList();
        return road;
    }

    public List<String> getStartRoadName(String orgIds, String provinceName, String cityName, String areaName,
                                         String endRoadName, String roadName) throws Exception {
        String hql = "select distinct c.CoverStartRoad from tb_cover c where (c.CoverOrgId in (" + orgIds + ") or " +
                "c.CoverMainOrgId in (" + orgIds + "))";
        if (!provinceName.equals("-1")) {
            hql += " and c.CoverProvince ='" + provinceName + "'";
        }
        if (!cityName.equals("-1")) {
            hql += " and c.CoverCity ='" + cityName + "'";
        }
        if (!areaName.equals("-1")) {
            hql += " and c.CoverArea = '" + areaName + "'";
        }
        if (!endRoadName.equals("-1")) {
            hql += " and c.CoverEndRoad = '" + endRoadName + "'";
        }
        if (!roadName.equals("-1")) {
            hql += " and c.CoverRoadName = '" + roadName + "'";
        }
        hql += " order by convert(c.CoverStartRoad using gbk) asc";
        Query query = em.createNativeQuery(hql);
        List<String> road = query.getResultList();
        return road;
    }

    public List<String> getEndRoadName(String orgIds, String startRoad, String provinceName, String cityName,
                                       String areaName, String roadName) throws Exception {
        String hql = "select distinct c.CoverEndRoad from tb_cover c where (c.CoverOrgId in (" + orgIds + ") or " +
                "c.CoverMainOrgId in (" + orgIds + "))";
        if (!provinceName.equals("-1")) {
            hql += " and c.CoverProvince ='" + provinceName + "'";
        }
        if (!cityName.equals("-1")) {
            hql += " and c.CoverCity ='" + cityName + "'";
        }
        if (!areaName.equals("-1")) {
            hql += " and c.CoverArea = '" + areaName + "'";
        }
        if (!startRoad.equals("-1")) {
            hql += " and c.CoverStartRoad = '" + startRoad + "'";
        }
        if (!roadName.equals("-1")) {
            hql += " and c.CoverRoadName = '" + roadName + "'";
        }
        hql += " order by convert(c.CoverEndRoad using gbk) asc";
        Query query = em.createNativeQuery(hql);
        List<String> road = query.getResultList();
        return road;
    }

    public List<Integer> getCoverTypeCounts(String orgIds, String time, String province, String city, String area, String road) throws Exception {
        String[] timeLimit = {"", ""};
        timeLimit = time.split(" - ");
        String hql = "select c.CoverShape from tb_cover c  where (c.CoverOrgId in (" + orgIds + ") or " +
                "c.CoverMainOrgId in (" + orgIds + ")) AND (c.CoverInstallTime between '" + timeLimit[0] + "' and '" + timeLimit[1] + "') " +
                " and c.CoverProvince like '%" + province + "%' and c.CoverCity like '%" + city + "%' " +
                " and c.CoverArea like '%" + area + "%' and c.CoverRoadName like '%" + road + "%'   ORDER BY c.CoverShape";
        Query query = em.createNativeQuery(hql);
        List<Integer> counts = query.getResultList();
        return counts;
    }
}
